<template>
    <el-card shadow="never" class="border-0">
      <!-- 搜索 -->
      <el-form :model="searchForm" label-width="80px" class="mb-3" size="small">
        <el-row :gutter="20">
          <el-col :span="5" :offset="0">
            <el-form-item label="零件名称">
              <el-input v-model="searchForm.partName" placeholder="零件名称" clearable></el-input>
            </el-form-item>
          </el-col>

          <!-- <el-col :span="5">
            <el-form-item label="设备类型">
              <el-select v-model="searchForm.deviceTypeId" filterable placeholder="请选择设备类型">
                <el-option
                  v-for="item in deviceTypeDic"
                  :key="item.deviceTypeId"
                  :label="item.deviceTypeName"
                  :value="item.deviceTypeId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col> -->

          <el-col :span="10">
            <div class="flex items-center justify-end">
              <el-button type="primary" @click="initTableData(1)">搜索</el-button>
              <el-button @click="resetSearchForm">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
  
      <!-- 新增|刷新 -->
      <div class="flex items-center justify-between mb-4">
        <div>
          <!-- <el-button type="primary" size="small" @click="toDeviceType">设备类型管理</el-button> -->
          <el-button type="primary" size="small" @click="handleCreate">新增零件类型</el-button>
        </div>
        <el-tooltip effect="dark" content="刷新数据" placement="top">
          <el-button text @click="initTableData">
            <el-icon :size="20">
              <Refresh />
            </el-icon>
          </el-button>
        </el-tooltip>
      </div>
  
      <!-- 表格数据 -->
      <el-table :data="tableData" stripe style="width: 100%" v-loading="loading">

        <el-table-column label="零件类型名称" align="center">
          <template #default="{ row }">
            {{ row.partName }}
          </template>
        </el-table-column>
  
        <el-table-column label="新件库存数量" align="center">
          <template #default="{ row }">
            {{ row.newPartNum }}
          </template>
        </el-table-column>
  
        <el-table-column label="坏件库存数量" align="center">
          <template #default="{ row }">
            {{ row.damagePartNum }}
          </template>
        </el-table-column>
  
        <el-table-column label="修复件库存数量" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.rebuiltPartNum }}
          </template>
        </el-table-column>

        <!-- <el-table-column label="设备类型" align="center">
          <template #default="{ row }">
            {{ row.deviceTypeName }}
          </template>
        </el-table-column> -->
  
        <el-table-column label="备注" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.remarks }}
          </template>
        </el-table-column>
  
        <el-table-column label="信息创建时间" align="center">
          <template #default="{ row }">
            {{ dateFormatter(row.createTime) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="320" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" text @click="handleEdit(scope.row)">修改</el-button>
            <el-button type="primary" size="small" text @click="handlePartIn(scope.row)">入库</el-button>
            <el-button type="primary" size="small" text @click="handlePartOut(scope.row)">出库</el-button>
            <el-button type="primary" size="small" text @click="handleRecord(scope.row)">记录</el-button>
            <el-popconfirm title="是否要删除该零件？" confirmButtonText="确认" cancelButtonText="取消"
              @confirm="handleDelete(scope.row.partId)">
              <template #reference>
                <el-button text type="primary" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 分页组件 -->
      <div class="flex items-center justify-center mt-5">
        <el-pagination background layout="prev, pager ,next" :total="total" :current-page="currentPage" :page-size="limit"
          @current-change="initTableData" />
      </div>
  
      <!-- 新增|修改弹窗 -->
      <FormDrawer ref="formDrawerRef" :title="drawerTitle" @submit="handleSubmit">
  
        <el-form :model="form" ref="formRef" :rules="rules" label-width="120px" :inline="false">
          <el-form-item label="零件类型名称" prop="partName">
            <el-input v-model="form.partName" placeholder="零件类型名称"></el-input>
          </el-form-item>
  
          <!-- <el-form-item label="设备类型" prop="deviceTypeId">
            <el-select v-model="form.deviceTypeId" filterable placeholder="请选择设备类型">
              <el-option
                v-for="item in deviceTypeDic"
                :key="item.deviceTypeId"
                :label="item.deviceTypeName"
                :value="item.deviceTypeId">
              </el-option>
            </el-select>
          </el-form-item> -->
  
          <el-form-item label="备注" prop="remarks">
            <el-input type="textarea" v-model="form.remarks" placeholder="备注"></el-input>
          </el-form-item>
        </el-form>
      </FormDrawer>
  
      <!-- 入库|出库弹窗 -->
      <FormDrawer ref="formPartInOrOutDrawerRef" :title="inOrOutTitle" @submit="handleInOrOutSubmit">
        <el-form :model="formPartInOrOut" ref="formPartInOrOutRef" :rules="inOrOutrules" label-width="120px" :inline="false">

          <!-- 0维修, 1销售，2新生产，3其他 -->
          <el-form-item v-if="inOrOutTitle=='入库'" label="操作类型" prop="opType">
            <el-select v-model="formPartInOrOut.opType" filterable placeholder="请选择操作类型">
              <el-option
                v-for="item in opInTypeDic"
                :key="item.key"
                :label="item.value"
                :value="item.key">
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 操作类型, 0维修, 1销售 -->
          <el-form-item v-else label="操作类型" prop="opType">
            <el-select v-model="formPartInOrOut.opType" filterable placeholder="请选择操作类型">
              <el-option
                v-for="item in opOutTypeDic"
                :key="item.key"
                :label="item.value"
                :value="item.key">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="设备状态" prop="deviceStatus">
            <el-select v-model="formPartInOrOut.deviceStatus" filterable placeholder="请选择设备状态">
              <el-option
                v-for="item in partStatusDic"
                :key="item.key"
                :label="item.value"
                :value="item.key">
              </el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="数量" prop="num">
            <el-input
              type="number"
              placeholder="数量"
              v-model="formPartInOrOut.num"
              :min="1"
              :max="999"
            ></el-input>
          </el-form-item>

          <!-- 入库-新生产不展示选择申请人 -->
          <el-form-item v-if="formPartInOrOut.opType != 2" label="申请人" prop="userId">
              <el-button @click="dialogTableVisible_user = true">
                  {{ checkedUser == null ? '选择申请人' : checkedUser.realName }}
              </el-button>
          </el-form-item>

          <!-- <el-form-item v-if="inOrOut == 1 || (inOrOut == 0 && formPartInOrOut.opType == 1) " label="选择工单" prop="orderId">
              <el-button @click="dialogTableVisible_order = true">
                  {{ checkedOrder == null ? '选择工单' : checkedOrder.orderName }}
              </el-button>
          </el-form-item> -->

          <el-form-item label="备注" prop="remarks">
            <el-input type="textarea" v-model="formPartInOrOut.remarks" placeholder="备注"></el-input>
          </el-form-item>
        </el-form>
      </FormDrawer>
    </el-card>

    <!-- 选择工单弹窗 -->
    <el-dialog v-model="dialogTableVisible_order" title="选择工单" width="70%" align-center>
      <SelectOrder @getCheckedOrder="getCheckedOrder" />
      <template #footer>
          <div class="dialog-footer">
              <el-button type="primary" @click="dialogTableVisible_order = false">
                  确认
              </el-button>
          </div>
      </template>
    </el-dialog>

    <!-- 选择申请人弹窗 -->
    <!-- <el-dialog v-model="dialogTableVisible_user" title="选择申请人" width="70%" align-center>
      <SelectUser v-if="dialogTableVisible_user" @getCheckedUser="getCheckedUser" />
      <template #footer>
          <div class="dialog-footer">
              <el-button type="primary" @click="dialogTableVisible_user = false">
                  确认
              </el-button>
          </div>
      </template>
    </el-dialog> -->

    <!-- 选择申请人弹窗 -->
    <SystemDialog title="选择申请人" :visible="dialogTableVisible_user" :height="60" :width="70"
      @on-close="dialogTableVisible_user = false" @on-confirm="dialogTableVisible_user = false">
      <template v-slot:content>
        <SelectUser v-if="dialogTableVisible_user" @getCheckedUser="getCheckedUser" />
      </template>
    </SystemDialog>

    <!-- 查看出入库记录弹窗 -->
    <el-dialog v-model="dialogTableVisible_record" title="出入库记录" width="70%" align-center>
      <!-- 是否零件, 0设备, 1零件 -->
      <ShowRecord v-if="dialogTableVisible_record" :deviceId="showRecord_deviceId" :isPart="1" />
      <template #footer>
          <div class="dialog-footer">
              <el-button type="primary" @click="dialogTableVisible_record = false">
                  关闭
              </el-button>
          </div>
      </template>
    </el-dialog>
  </template>

  <script setup>
  import { ref, reactive, computed, onMounted } from "vue"
  import FormDrawer from "~/components/FormDrawer.vue";
  import SystemDialog from "~/components/SystemDialog.vue";
  import SelectOrder from "~/components/select-order.vue";
  import SelectUser from "~/components/select-user.vue";
  import ShowRecord from "~/components/show-records.vue";
  import {toast, toastWarn} from "~/composables/util"
  import { dateFormatter } from '~/utils/common.js'
  import { getUserInfo } from '~/utils/userInfo.js'
  import { getDevicePartList,getDeviceTypeList,addDevicePart,updateDevicePart,partIn,partOut,deleteDevicePart } from "~/api/supply"

  // 操作类型, 0维修, 1销售，2新生产，3其他
  const opInTypeDic = ref([{"key":2,"value":"新生产"},{"key":1,"value":"工单"},{"key":0,"value":"维修"}])

  // 操作类型, 0维修, 1销售
  const opOutTypeDic = ref([{"key":1,"value":"工单"},{"key":0,"value":"维修"}])

  // 设备状态字典数据 1新件，2坏件，3修复件
  const partStatusDic = ref([{"key":0,"value":"新件"},{"key":1,"value":"坏件"},{"key":2,"value":"修复件"}])

  // 当前用户信息
  const userInfo = ref({})

  // 分页
  const currentPage = ref(1)
  const total = ref(0)
  const limit = ref(10)

  //设备类型字典数据
  const deviceTypeDic = ref([])

  // 查询条件
  const searchForm = reactive({
    partName: "",
    deviceTypeId: null,
    page: currentPage.value,
    size: limit.value,
  })
  // 重置搜索框
  const resetSearchForm = () => {
    searchForm.partName = ""
    searchForm.deviceTypeId = null
    initTableData(1)
  }
  
  const tableData = ref([])
  const loading = ref(false)
  
  
  // 生命周期函数
  onMounted(() => {
    //获取当前用户信息
    userInfo.value = getUserInfo()

    //初始化设备类型
    initDeviceType()

    //初始化列表数据
    initTableData()
  })

  //初始化设备类型
  function initDeviceType(){
    //查询全部
    let paramIo = {
      page: 1,
      size: 100,
    }
    getDeviceTypeList(paramIo)
      .then(res => {
          if(res){
            deviceTypeDic.value = res.records      
          }
      })
    .finally(() => {
      loading.value = false
    })
  }
  
  // 获取数据
  function initTableData(p = null) {
    //指定页码是否为空
    if (typeof p == "number") {
      currentPage.value = p
    }
  
    loading.value = true
    searchForm.page = currentPage.value

    getDevicePartList(searchForm)
      .then(res => {
          if(res){
            tableData.value = res.records      
            total.value = res.total
          }else{
            tableData.value = []  
            total.value = 0
          }
      })
      .finally(() => {
        loading.value = false
      })
  }
  
  // 删除
  const handleDelete = (id) => {
    loading.value = true
    deleteDevicePart(id).then(res => {
      toast("删除成功")
      initTableData()
    })
      .finally(() => {
        loading.value = false
      })
  }
  
  // 表单部分-----------------
  const formDrawerRef = ref(null)
  const formRef = ref(null)
  const form = reactive({
    partName: "",
    deviceTypeId: null,
    remarks:""
  })
  //执行表单校验
  const rules = {
    partName: [
      { required: true, message: '零件名称不能为空', trigger: 'change' }
    ],
    deviceTypeId: [
      { required: true, message: '设备类型不能为空', trigger: 'change' }
    ],
  }
  
  //是否是编辑弹窗
  const editId = ref(0)
  const drawerTitle = computed(() => editId.value ? "修改" : "新增")
  
  //提交表单
  const handleSubmit = () => {
    //表单校验
    formRef.value.validate((valid) => {
      if (!valid) return

      //loading
      formDrawerRef.value.showLoading()
  
      //根据是否是修改标记，判断执行新增接口还是修改接口
      const fun = editId.value ? updateDevicePart(editId.value, form) : addDevicePart(form)

      fun.then(res => {
        toast(drawerTitle.value + "成功")
        // 修改刷新当前页，新增刷新第一页
        initTableData(editId.value ? false : 1)
        formDrawerRef.value.close()
      })
      .finally(() => {
        //close loading
        formDrawerRef.value.hideLoading()
      })
    })
  }
  // 表单部分-----------------

  
  // 重置表单
  function resetForm(row = false) {
    if (formRef.value) formRef.value.resetFields()
    if (row) {
      for (const key in form) {
        form[key] = row[key]
      }
    }
  }
  
  // 新增按钮点击事件
  const handleCreate = () => {
    //修改标记置为0
    editId.value = 0
    resetForm({
        partName: "",
        deviceTypeId: null,
        remarks:""
    })
    //打开弹窗
    formDrawerRef.value.open()
  }
  
  // 编辑
  const handleEdit = (row) => {
    editId.value = row.partId
    resetForm(row)
    formDrawerRef.value.open()
  }

  // 入库
  const handlePartIn = (row) => {
    resetPartInOrOutForm(row)
    inOrOut.value = 0
    formPartInOrOut.opType = 2
    formPartInOrOutDrawerRef.value.open()
  }

  // 出库
  const handlePartOut = (row) => {
    resetPartInOrOutForm(row)
    inOrOut.value = 1
    formPartInOrOut.opType = 1
    formPartInOrOutDrawerRef.value.open()
  }

  // 出入库记录
  const handleRecord = (row) => {
      showRecord_deviceId.value = row.partId
      dialogTableVisible_record.value = true
  }

  // 查看出入库记录弹窗-----------
  const dialogTableVisible_record = ref(false)
  const showRecord_deviceId = ref(0)
  // 查看出入库记录弹窗-----------

  // 出入库表单部分------------
  // 0入库 1出库
  const inOrOut = ref(0)
  const inOrOutTitle = computed(() => inOrOut.value ? "出库" : "入库")
  const formPartInOrOutDrawerRef = ref(null)
  const formPartInOrOutRef = ref(null)
  const formPartInOrOut = reactive({
      //操作类型
      opType: 1,
      //设备状态,设备状态,0新件，1坏件，2修复件
      deviceStatus: 0,
      //出入库数量
      num: null,
      //工单ID
      orderId: null,
      //项目ID
      projectId: null,
      //客户ID
      customerId: null,
      //人员ID
      userId: null,
      //人员姓名
      userName: null,
      remarks: null,

      //赋值入参
      deviceTypeId: null,
      partId: null
  })
  function resetPartInOrOutForm(row) {
    if (formPartInOrOutRef.value) {
      formPartInOrOutRef.value.resetFields()
    }
    //设备状态,设备状态,0新件，1坏件，2修复件
    formPartInOrOut.deviceStatus = 0
    formPartInOrOut.num = null
    formPartInOrOut.orderId = null
    formPartInOrOut.projectId = null
    formPartInOrOut.customerId = null
    formPartInOrOut.userId = null
    formPartInOrOut.userName = null
    formPartInOrOut.remarks = null

    //将工单信息清空
    checkedOrder.value = null
    //将申请人信息清空
    checkedUser.value = null

    //赋值入参
    formPartInOrOut.deviceTypeId = row.deviceTypeId
    formPartInOrOut.partId = row.partId
  }
  
  const inOrOutrules = {
    opType: [
      { required: true, message: '操作类型不能为空', trigger: 'change' }
    ],
    deviceStatus: [
      { required: true, message: '设备状态不能为空', trigger: 'change' }
    ],
    num: [
      { required: true, message: '数量不能为空', trigger: 'change' }
    ],
    userId: [
      { required: true, message: '申请人不能为空', trigger: 'change' }
    ],
    orderId: [
      { required: true, message: '工单信息不能为空', trigger: 'change' }
    ]
  }
  //提交表单
  const handleInOrOutSubmit = () => {
    //表单校验
    formPartInOrOutRef.value.validate((valid) => {
      if (!valid) return
      //loading
      formPartInOrOutDrawerRef.value.showLoading()

      //入库-新设备入库
      if(inOrOut.value == 0 && formPartInOrOut.opType == 2){
        formPartInOrOut.userId = userInfo.value.id
        formPartInOrOut.userName = userInfo.value.realName
      }

      //console.log("出入库请求参数===>",JSON.stringify(formPartInOrOut))
      //出入库
      const fun = inOrOut.value==0?partIn(formPartInOrOut):partOut(formPartInOrOut)
      fun.then(res => {
        toast(inOrOutTitle.value + "成功")
        initTableData(false)
        formPartInOrOutDrawerRef.value.close()
      })
      .finally(() => {
        formPartInOrOutDrawerRef.value.hideLoading()
      })
    })
  }

  //选择申请人
  const dialogTableVisible_user = ref(false)
  const checkedUser = ref(null)
  //获取选择的申请人
  function getCheckedUser(data) {
    // console.log('checked user: ', JSON.stringify(data))
    if (data != null) {
        formPartInOrOut.userId = data.id
        formPartInOrOut.userName = data.realName
        //显示内容
        checkedUser.value = data
    }
  }

  //选择工单弹窗
  const dialogTableVisible_order = ref(false)
  const checkedOrder = ref(null)
  //获取选择的工单
  function getCheckedOrder(data) {
      // console.log('checked order: ', JSON.stringify(data))
      if (data != null) {
          //入库
          formPartInOrOut.orderId = data.orderId
          formPartInOrOut.projectId = data.projectId
          formPartInOrOut.customerId = data.customerId
          //显示内容
          checkedOrder.value = data
      }
  }
  // 出入库表单部分------------
  </script>